import { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import {
  Form,
  Input,
  ErrorBlock,
  List,
  Card,
  Grid,
  Dialog,
  Toast,
} from "antd-mobile";
import { BottomBtn } from "@components";
import { REQUIRED_RULE, BARCODE_PARSER } from "@common/constants";
import { createAction, callNativeApi } from "@common/utils";
import {
  PUSH_PAGE_STACK,
  POP_PAGE_STACK,
  SET_SCAN_DATA,
} from "@store/global-state/action-types";
import {
  SAGA_PROD_INBOUND_LOAD_MIX_OPS_FORM_DATA,
  SAGA_PROD_INBOUND_FINISH_MIX_OPS,
  SAGA_PROD_INBOUND_STASH_MIX_OPS_DATA,
} from "@store/prod-inbound/saga-types";
import { CLEAR_PROD_INBOUND_OPS_FORM_DATA } from "@store/prod-inbound/action-types";

const ScanOpsPallet = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const opsFormData = useSelector((state) => state.prodInbound.opsFormData);
  const scandata = useSelector((state) => state.globalState.scandata);
  const [form] = Form.useForm();
  const [items, setItems] = useState([]);

  const Description = ({ title, record }) => (
    <Card title={title}>
      <Grid columns={2} gap={12}>
        <Grid.Item>物料条码</Grid.Item>
        <Grid.Item>{record.itemBarcode}</Grid.Item>
        <Grid.Item>物料编码</Grid.Item>
        <Grid.Item>{record.itemCode}</Grid.Item>
        <Grid.Item>物料名称</Grid.Item>
        <Grid.Item>{record.itemName}</Grid.Item>
        <Grid.Item>数量/单位</Grid.Item>
        <Grid.Item>{`${record.qty} ${record.itemUnit}/${record.pkgUnit}`}</Grid.Item>
      </Grid>
    </Card>
  );

  const ItemTitle = () => (
    <>
      <span>物料信息</span>
      <span style={{ float: "right" }}>
        累计提交数据: {opsFormData?.recordNum ? opsFormData.recordNum : 0}条
      </span>
    </>
  );

  const setFields = ({ barcode, parseResult }) => {
    let { items } = parseResult;
    form.setFields([{ name: "palletBarcode", value: barcode }]);
    setItems(items);
  };

  const setLocFields = ({ barcode, parseResult }) => {
    let { warehouseId, locationName } = parseResult;
    if (opsFormData.warehouseId !== warehouseId) {
      Dialog.alert({ content: "库位与当前仓库不匹配!" });
      return;
    }
    form.setFields([
      { name: "locationBarcode", value: barcode },
      { name: "locationName", value: locationName },
    ]);
  };

  useEffect(() => {
    dispatch(
      createAction(SAGA_PROD_INBOUND_LOAD_MIX_OPS_FORM_DATA, {
        id: searchParams.get("id"),
      })
    );
    return () => {
      dispatch(createAction(SET_SCAN_DATA, null));
      dispatch(createAction(CLEAR_PROD_INBOUND_OPS_FORM_DATA));
    };
  }, []);

  useEffect(() => {
    if (scandata) {
      callNativeApi({
        classFullName: BARCODE_PARSER,
        action: "parse",
        params: { barcode: scandata, bizType: "MIX_INBOUND_PALLET" },
        needNonce: false,
      })
        .then((resp) => {
          let result = resp.data ? resp.data.payload : resp.payload;
          if (result.ruleType === "PALLET") {
            // 托码
            setFields({
              barcode: scandata,
              parseResult: result,
            });
          } else if (result.ruleType === "LOCATION") {
            // 库位码
            setLocFields({
              barcode: scandata,
              parseResult: result,
            });
          }
          dispatch(createAction(SET_SCAN_DATA, null));
          return;
        })
        .catch((error) => console.log(error));
    }
  }, [scandata]);

  const handleContinue = () => {
    form
      .validateFields()
      .then(() => {
        let { locationBarcode, palletBarcode } = form.getFieldValue();
        dispatch(
          createAction(SAGA_PROD_INBOUND_STASH_MIX_OPS_DATA, {
            id: opsFormData.id,
            palletBarcode,
            locationBarcode,
            callback: () => {
              Toast.show({
                icon: "success",
                content: "保存成功",
                maskClickable: false,
              });
              form.setFields([
                { name: "locationBarcode", value: "" },
                { name: "locationName", value: "" },
                { name: "palletBarcode", value: "" },
              ]);
              setItems([]);
            },
          })
        );
        return;
      })
      .catch((error) => console.log(error));
  };

  const openDetails = () => {
    let path = "/app/prod-inbound/scan-directly-details";
    if (opsFormData.id) {
      path += `?id=${opsFormData.id}`;
    }
    navigate(path);
    dispatch(createAction(PUSH_PAGE_STACK, path));
  };

  const handleFinish = () => {
    dispatch(
      createAction(SAGA_PROD_INBOUND_FINISH_MIX_OPS, {
        id: opsFormData.id,
        callback: () => {
          dispatch(createAction(POP_PAGE_STACK, navigate));
        },
      })
    );
  };

  return (
    <>
      <div style={{ marginBottom: "75px" }}>
        <Form form={form} mode="card">
          <Form.Header>基本信息</Form.Header>
          <Form.Item label="仓库">{opsFormData?.warehouseName}</Form.Item>
          <Form.Item label="业务类型">生产入库</Form.Item>
          <Form.Item name="locationName" label="库位" rules={REQUIRED_RULE}>
            <Input placeholder="扫码获取" readOnly />
          </Form.Item>
          <Form.Item name="palletBarcode" label="托码" rules={REQUIRED_RULE}>
            <Input placeholder="扫码获取" readOnly />
          </Form.Item>
          {items.length === 0 ? (
            <Form.Header>
              <ItemTitle />
            </Form.Header>
          ) : null}
          {items.length === 0 ? (
            <ErrorBlock status="empty" title="暂无数据" description="" />
          ) : null}
        </Form>
        {items.length > 0 ? (
          <List header={<ItemTitle />}>
            {items.map((i, idx) => (
              <List.Item
                key={idx}
                style={{ backgroundColor: "#F5F5F5" }}
                description={
                  <Description
                    title={`${idx + 1}/${items.length}`}
                    record={i}
                  />
                }
              />
            ))}
          </List>
        ) : null}
      </div>
      <BottomBtn
        items={[
          { btnTxt: "继续", color: "danger", handler: handleContinue },
          {
            btnTxt: "明细",
            disabled: !(opsFormData?.recordNum > 0),
            handler: openDetails,
          },
          {
            btnTxt: "完成",
            color: "primary",
            disabled: !(opsFormData?.recordNum > 0),
            handler: handleFinish,
          },
        ]}
      />
    </>
  );
};

export default ScanOpsPallet;
